package com.learnyou.server.xingzuo.common.helper;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.Week;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 二进制数据处理
 */
@Slf4j
public class BinaryDigitHelper {

    private static final int WEEK_LENGTH = 7;
    /**
     * 从二进制位转换为数字
     * @param trueDigits 为【真】的二进制位(从左往右计算)
     * @param length 二进制长度
     * @return 数字
     */
    public static int from(List<Integer> trueDigits, int length) {
        int num = 0;
        if (length > 0 && CollectionUtil.isNotEmpty(trueDigits)) {
            for(Integer trueDigit : trueDigits) {
                if (length - trueDigit >= 0) {
                    num += (1<<(length - trueDigit ));
                }
            }
        }
        return num;
    }

    /**
     * 数字转换成 为【真】的二进制位list
     * @param num 数字
     * @param length 二进制长度
     * @return 为【真】的二进制位list（从左往右）
     */
    public static List<Integer> toTrueDigitList(int num, int length) {
        List<Integer> trueDigitList = new ArrayList<>();
        if (length > 0 && num > 0) {
            for(int i = 0; i< length; i++) {
                int digitNumber = 1<< i;
                if ((num & digitNumber) == digitNumber) {
                    // 从左往右第几位
                    trueDigitList.add(length - i);
                }
            }
        }
        return trueDigitList;
    }

    public static int weekNumFrom(List<Integer> trueDigits) {
        return from(trueDigits, WEEK_LENGTH);
    }

    public static List<Integer> weekNumTo(int num) {
        return toTrueDigitList(num, WEEK_LENGTH);
    }

    /**
     * 星期数字转中文
     * @param num
     * @return
     */
    public static List<String> weekNumToChineseName(int num){
        List<Integer> list = weekNumTo(num);
        return list.stream()
                .sorted(Comparator.comparingInt(Integer::intValue))
                .map(t-> Week.of(DayOfWeek.of(t)).toChinese("")).collect(Collectors.toList());
    }
}
